﻿#include <zyD2DRenderer.h>


// 创建设备资源（工厂、渲染目标、画刷等）
void DarkMoonUI::zyD2DRenderer::CreateDeviceResources() {
    // 如果已有资源先释放
    SafeRelease(m_pRenderTarget);
    SafeRelease(m_pDefaultBrush);

    // 1. 创建D2D工厂（如果不存在）
    if (!m_pD2DFactory) {
        HRESULT hr = D2D1CreateFactory(
            D2D1_FACTORY_TYPE_SINGLE_THREADED,
            __uuidof(ID2D1Factory1),
            nullptr,
            (void**)&m_pD2DFactory
        );
        //if (FAILED(hr)) throw std::runtime_error("D2D工厂创建失败");
    }

    // 2. 创建DirectWrite工厂（如果不存在）
    if (!m_pDWriteFactory) {
        HRESULT hr = DWriteCreateFactory(
            DWRITE_FACTORY_TYPE_SHARED,
            __uuidof(IDWriteFactory),
            (IUnknown**)&m_pDWriteFactory
        );
        if (FAILED(hr)) {
            SafeRelease(m_pD2DFactory);
            //throw std::runtime_error("DWrite工厂创建失败");
        }
    }

    // 3. 创建窗口关联的渲染目标
    D2D1_RENDER_TARGET_PROPERTIES rtProps = D2D1::RenderTargetProperties(
        D2D1_RENDER_TARGET_TYPE_DEFAULT,
        D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED));

    D2D1_HWND_RENDER_TARGET_PROPERTIES hwndProps =
        D2D1::HwndRenderTargetProperties(m_hWnd, m_size);

    HRESULT hr = m_pD2DFactory->CreateHwndRenderTarget(
        &rtProps,
        &hwndProps,
        &m_pRenderTarget
    );
    if (FAILED(hr)) {
        SafeRelease(m_pD2DFactory);
        SafeRelease(m_pDWriteFactory);
        //throw std::runtime_error("渲染目标创建失败");
    }

    // 4. 创建默认画刷
    hr = m_pRenderTarget->CreateSolidColorBrush(
        D2D1::ColorF(D2D1::ColorF::Black),
        &m_pDefaultBrush
    );
    if (FAILED(hr)) {
        SafeRelease(m_pRenderTarget);
        SafeRelease(m_pD2DFactory);
        SafeRelease(m_pDWriteFactory);
        //throw std::runtime_error("默认画刷创建失败");
    }
}

// 构造函数
DarkMoonUI::zyD2DRenderer::zyD2DRenderer(HWND hWnd, UINT width, UINT height)
    : m_hWnd(hWnd), m_size({ width, height }),
    m_pD2DFactory(nullptr),
    m_pDWriteFactory(nullptr),
    m_pRenderTarget(nullptr),
    m_pDefaultBrush(nullptr) {
    CreateDeviceResources();
}

// 析构函数
DarkMoonUI::zyD2DRenderer::~zyD2DRenderer() {
    SafeRelease(m_pDefaultBrush);
    SafeRelease(m_pRenderTarget);
    SafeRelease(m_pDWriteFactory);
    SafeRelease(m_pD2DFactory);
}

// 开始绘制
void DarkMoonUI::zyD2DRenderer::BeginDraw() {
    if (m_pRenderTarget) {
        m_pRenderTarget->BeginDraw();
        m_pRenderTarget->SetAntialiasMode(D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
        m_pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
    }
}

// 结束绘制
void DarkMoonUI::zyD2DRenderer::EndDraw() {
    if (!m_pRenderTarget) return;

    HRESULT hr = m_pRenderTarget->EndDraw();

    // 设备丢失处理
    if (hr == D2DERR_RECREATE_TARGET) {
        SafeRelease(m_pDefaultBrush);
        SafeRelease(m_pRenderTarget);
        CreateDeviceResources();
    }
}

// 清空画布
void DarkMoonUI::zyD2DRenderer::Clear(D2D1_COLOR_F color) {
    if (m_pRenderTarget) {
        m_pRenderTarget->Clear(&color);
    }
}

// 绘制矩形
void DarkMoonUI::zyD2DRenderer::DrawRectangle(const D2D1_RECT_F& rect,
    D2D1_COLOR_F color, float strokeWidth) {
    if (m_pRenderTarget && m_pDefaultBrush) {
        m_pDefaultBrush->SetColor(color);
        m_pRenderTarget->DrawRectangle(rect, m_pDefaultBrush, strokeWidth);
    }
}

// 窗口尺寸调整
void DarkMoonUI::zyD2DRenderer::Resize(UINT width, UINT height) {
    m_size = { width, height };
    if (m_pRenderTarget) {
        HRESULT hr = m_pRenderTarget->Resize(m_size);
        if (FAILED(hr)) {
            SafeRelease(m_pRenderTarget);
        }
    }
}

// 创建文本格式
IDWriteTextFormat* DarkMoonUI::zyD2DRenderer::CreateTextFormat(const WCHAR* fontName, float fontSize,
    DWRITE_FONT_WEIGHT fontWeight,DWRITE_FONT_STYLE fontStyle,DWRITE_FONT_STRETCH fontStretch){
    IDWriteTextFormat* pFormat = nullptr;
    if (m_pDWriteFactory) {
        HRESULT hr = m_pDWriteFactory->CreateTextFormat( fontName, nullptr,fontWeight, fontStyle,
            fontStretch, fontSize, L"",  &pFormat
        );
        if (FAILED(hr)) pFormat = nullptr;
    }
    return pFormat;
}

// 绘制阴影
void DarkMoonUI::zyD2DRenderer::DrawShadow(const D2D1_RECT_F& rect, float cornerRadius, float blurRadius, 
    D2D1_COLOR_F shadowColor, D2D1_POINT_2F shadowOffset, float opacity) {
    D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(rect, cornerRadius, cornerRadius);

    // 创建一个位图渲染目标
    ID2D1BitmapRenderTarget* pBitmapRenderTarget = nullptr;
    HRESULT hr = m_pRenderTarget->CreateCompatibleRenderTarget(&pBitmapRenderTarget);

    if (SUCCEEDED(hr)) {
        // 绘制圆角矩形到位图上
        pBitmapRenderTarget->BeginDraw();
        pBitmapRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White, 0.0f)); // 透明背景
        m_pDefaultBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Black, opacity));
        pBitmapRenderTarget->FillRoundedRectangle(roundedRect, m_pDefaultBrush);
        pBitmapRenderTarget->EndDraw();

        // 获取位图
        ID2D1Bitmap* pBitmap = nullptr;
        hr = pBitmapRenderTarget->GetBitmap(&pBitmap);

        if (SUCCEEDED(hr)) {
            // 创建阴影效果
            ID2D1Effect* pShadowEffect = nullptr;
            ID2D1DeviceContext* pDC = nullptr;
            if (SUCCEEDED(m_pRenderTarget->QueryInterface(__uuidof(ID2D1DeviceContext), (void**)&pDC))) {
                if (SUCCEEDED(pDC->CreateEffect(CLSID_D2D1Shadow, &pShadowEffect))) {
                    // 设置阴影参数
                    pShadowEffect->SetInput(0, pBitmap);
                    pShadowEffect->SetValue(D2D1_SHADOW_PROP_COLOR, D2D1::Vector4F(shadowColor.r, shadowColor.g, shadowColor.b, shadowColor.a));
                    pShadowEffect->SetValue(D2D1_SHADOW_PROP_BLUR_STANDARD_DEVIATION, blurRadius);

                    // 绘制阴影（带偏移）
                    pDC->DrawImage(pShadowEffect, shadowOffset);

                    SafeRelease(pShadowEffect);
                }
                SafeRelease(pDC);
            }
            SafeRelease(pBitmap);
        }
        SafeRelease(pBitmapRenderTarget);
    }
}

void DarkMoonUI::zyD2DRenderer::FillRectangle(const D2D1_RECT_F& rect, D2D1_COLOR_F color) {
    m_pDefaultBrush->SetColor(color);
    m_pRenderTarget->FillRectangle(rect, m_pDefaultBrush);
}

void DarkMoonUI::zyD2DRenderer::DrawCircle(D2D1_POINT_2F center, float radius, D2D1_COLOR_F color, float strokeWidth ) {
    m_pDefaultBrush->SetColor(color);
    D2D1_ELLIPSE ellipse = D2D1::Ellipse(center, radius, radius);
    m_pRenderTarget->DrawEllipse(ellipse, m_pDefaultBrush, strokeWidth);
}

void DarkMoonUI::zyD2DRenderer::FillCircle(D2D1_POINT_2F center, float radius, D2D1_COLOR_F color) {
    m_pDefaultBrush->SetColor(color);
    D2D1_ELLIPSE ellipse = D2D1::Ellipse(center, radius, radius);
    m_pRenderTarget->FillEllipse(ellipse, m_pDefaultBrush);
}

void DarkMoonUI::zyD2DRenderer::DrawText(const WCHAR* text,const D2D1_RECT_F& layoutRect,
    IDWriteTextFormat* pFormat, D2D1_COLOR_F color) {
    m_pDefaultBrush->SetColor(color);
    m_pRenderTarget->DrawText(text, wcslen(text), pFormat, layoutRect, m_pDefaultBrush);
}

ID2D1Factory1* DarkMoonUI::zyD2DRenderer::GetD2DFactory1() const { return m_pD2DFactory; }
bool DarkMoonUI::zyD2DRenderer::SetD2DFactory1(ID2D1Factory1* pD2DFactory) {
    // 空指针检查
    if (pD2DFactory == nullptr) {
        return false;
    }

    // 线程安全保护
    //std::lock_guard<std::mutex> lock(m_mutex);

    // 释放旧的工厂对象
    if (m_pD2DFactory) {
        SafeRelease(m_pD2DFactory);
    }

    // 设置新的工厂对象
    m_pD2DFactory = pD2DFactory;

    return true;
}

ID2D1SolidColorBrush* DarkMoonUI::zyD2DRenderer::GetDefaultBrush() const { return m_pDefaultBrush; }

void DarkMoonUI::zyD2DRenderer::FillRoundedRectangle(const D2D1_RECT_F& rect,
    float radiusX, float radiusY, D2D1_COLOR_F color){
    m_pDefaultBrush->SetColor(color);
    D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(rect, radiusX, radiusY);
    m_pRenderTarget->FillRoundedRectangle(roundedRect, m_pDefaultBrush);
}


